//
//  KLBuyNowViewController.m
//  KunLun
//
//  Created by Mac on 2017/12/28.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "KLBuyNowViewController.h"
#import "KLDeflutAddressView.h"
#import "STAddressMangeController.h"
#import "KLOrderHeaderView.h"
#import "KLOrderTableViewCell.h"
#import "KLOrderFooterView.h"
#import "KLBuyNowFooterView.h"
#import "STActionSheet.h"
@interface KLBuyNowViewController ()<STActionSheetDelegate>
@property(nonatomic, strong) KLDeflutAddressView                     *header;
@property(nonatomic, strong) STLabel                     *moneyLable;//金额
@property(nonatomic, strong) STButton                     *cofrimButton;//购买或者删除
@end

@implementation KLBuyNowViewController


#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"确认订单";
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self sendDelfutAreaRequest];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.height = self.tableView.height - 50;
    [self configBootomeView];
    [self reloadData];
    //注册重用
    [self.tableView registerClass:[KLOrderHeaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    [self.tableView registerClass:[KLBuyNowFooterView class] forHeaderFooterViewReuseIdentifier:@"footer"];
    [self.tableView registerClass:[KLOrderTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
      [self.tableView.mj_header beginRefreshing];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    self.header = [[KLDeflutAddressView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 20)];
    [self.header addTarget:self action:@selector(onSlectedAddControl) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = self.header;
}
- (void)configBootomeView{
    UIView  * bootomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 50)];
    bootomView.bottom = UIScreenHeight;
    bootomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bootomView];
    [bootomView st_showTopShadow];
    [bootomView st_showBottomLine];

    __weak typeof(self) weakSelf =  self;
    self.cofrimButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 120, 49)
                                                  title:@"提交订单"
                                             titleColor:[UIColor whiteColor]
                                              titleFont:15
                                           cornerRadius:0
                                        backgroundColor:KL_BlueBackGroundColor
                                        backgroundImage:nil
                                                  image:nil];
    self.cofrimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.cofrimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedConfimButton];
    }];

    self.cofrimButton.right = UIScreenWidth;
    [bootomView addSubview:self.cofrimButton];
    
    self.moneyLable = [[STLabel alloc] initWithFrame:CGRectMake( 10, 0, self.cofrimButton.left - 20, 49)
                                                text:@"合计:$5698"
                                           textColor:KL_redColor
                                                font:13
                                         isSizetoFit:NO
                                       textAlignment:NSTextAlignmentLeft];
    self.moneyLable.attributedText = [self.moneyLable.text st_convertAttributeStringWithKeyWord:@"合计:"
                                                                                     attributes:@{NSForegroundColorAttributeName:KL_firstTextColor}];
    [bootomView addSubview:self.moneyLable];
    
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.dataSouce[section] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [KLOrderTableViewCell CellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return [KLOrderHeaderView headerHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return [KLBuyNowFooterView footerHeight];
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    KLOrderHeaderView * header = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    KLGoodDetailModel * model =  [self.dataSouce[section] firstObject];
    header.desLable.text = model.shops.shops_name;
    return header;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    KLBuyNowFooterView * footer = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer"];
    footer.backgroundColor = [UIColor whiteColor];
    footer.payLable.text = [NSString stringWithFormat:@"共计%ld类商品，应付款$%0.2f元",self.dataSouce[section].count,[self fetchSectionPrice:section]];
    return footer;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    KLOrderTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.backgroundColor = [UIColor whiteColor];
    cell.detailModel = self.dataSouce[indexPath.section][indexPath.row];
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --Action Method
- (void)onSlectedAddControl{
    [self.navigationController pushViewController:[STAddressMangeController new] animated:YES];
}
- (void)onSelectedConfimButton{
    if (!self.header.model) {
        [SVProgressHUD showErrorWithStatus:@"您还没有选择地址"];
        return;
    }
    if (![self.from isEqualToString:@"cart"]) {
        KLGoodDetailModel * model = self.dataSouce.firstObject.firstObject;
        if (model.classification.integerValue == 4 ) {
            [self sendMakeOrderButWillNotPayRequest];
            return;
        }
    }
    STActionSheet  * action = [STActionSheet actionSheetWithTitle:@"支付方式" buttonTitles:@[@"微信",@"支付宝"] cancelTitle:@"取消" delegate:self];
    [action show];
}
#pragma mark --STActionSheetDelegate
- (void)actionSheet:(STActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //微信
        [self sendOrderRequestWithType:@"wxpay"];
    }
    if (buttonIndex == 1) {
        //支付宝
        [self sendOrderRequestWithType:@"alipay"];
    }
 //   [self test];
}

#pragma mark --Private Method
- (CGFloat)fetchSectionPrice:(NSInteger)section{
    NSArray * array = self.dataSouce[section];
    CGFloat money = 0;
    for (KLGoodDetailModel * model in array) {
        if (model.discount_price.length) {
            money = model.discount_price.floatValue * model.num + money;

        }else{
            money = model.price.floatValue * model.num   + money;
        }
    }
    return money;
}
- (CGFloat)allMoney{
    CGFloat money = 0;
    for (int i = 0; i<self.dataSouce.count;i++) {
        money = money + [self fetchSectionPrice:i];
    }
    return money;
}
- (NSDictionary*)configOrderDic{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    for (int i = 0; i<self.dataSouce.count;i++) {
        KLGoodDetailModel * model =  self.dataSouce[i].firstObject;
        NSMutableDictionary * goodDic = [NSMutableDictionary new];
        for (int k = 0 ; k < self.dataSouce[i].count; k ++) {
             KLGoodDetailModel * goodDetailModel =  self.dataSouce[i][k];
            
            [goodDic setObject:@(goodDetailModel.num).description forKey:goodDetailModel.goodID.description];
        }
       
        NSString * shopID = model.shops.gategoryID.description;
        [dic setObject:goodDic forKey:shopID];
    }
    return dic;
}
- (void)reloadData{
    self.moneyLable.text = [NSString stringWithFormat:@"合计:￥%0.2f",[self allMoney]];
    self.moneyLable.attributedText = [self.moneyLable.text st_convertAttributeStringWithKeyWord:@"合计:"
                                                                                     attributes:@{NSForegroundColorAttributeName:KL_firstTextColor}];
}
#pragma mark --NetWork Method
- (void)sendOrderRequestWithType:(NSString*)type{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:@"other" forKey:@"from"];
    if (self.from.length) {
         [dic setObject:self.from forKey:@"from"];
    }
    [dic setObject:self.header.model.name.length?self.header.model.name:@"" forKey:@"name"];
    [dic setObject:self.header.desLable.text.length?self.header.desLable.text:@"" forKey:@"address"];
    [dic setObject:self.header.model.telephone forKey:@"telephone"];
    [dic setObject:type forKey:@"pay_type"];
    
    NSDictionary * shopDic = [self configOrderDic];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:shopDic options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString * finsh =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    [dic setObject:finsh forKey:@"shop"];
    
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/order/order",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 if ([dataDic.allKeys containsObject:@"pay_data"]) {
                                                     if ([type isEqualToString:@"wxpay"]) {
                                                         NSDictionary * wechatDic = dataDic[@"pay_data"];
                                                         //wechat
                                                         PayReq *request = [PayReq new];
                                                         request.nonceStr = wechatDic[@"noncestr"];
                                                         request.package = wechatDic[@"package"];
                                                         request.partnerId = wechatDic[@"partnerid"];
                                                         request.prepayId = wechatDic[@"prepayid"];
                                                         request.sign = wechatDic[@"sign"];
                                                         request.timeStamp = [wechatDic[@"timestamp"] intValue];
                                                         [WXApi sendReq:request];
                                                     }else{
                                                         NSString * alipayStr = dataDic[@"pay_data"];
                                                         //alipay
                                                         [[AlipaySDK defaultService] payOrder:alipayStr fromScheme:@"KunLun" callback:^(NSDictionary *resultDic) {
                                                             NSLog(@"reslut = %@",resultDic);
                                                             //回调在appdelegate 中
                                                         }];
                                                     }

                                                 }
                                                 
                                                 [SVProgressHUD dismiss];
                                             } failure:^(NSString *stateCode, STError *error) {

                                                 [SVProgressHUD dismiss];
                                                  [SVProgressHUD showErrorWithStatus:error.desc];

                                             }];
}

- (void)sendDelfutAreaRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/user/getdefutl",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                   [self configSubView];
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 if ([dataDic.allKeys containsObject:@"address"]) {
                                                     STAddressModel * model = [STAddressModel mj_objectWithKeyValues:dataDic[@"address"]];
                                                     if (model.address_id.description.length) {
                                                         self.header.model = model;
                                                     }else{
                                                         self.header.model = nil;
                                                     }
                                                     
                                                 }
                                                
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                   [self configSubView];
                                                  self.header.model = nil;
                                                  [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 [self.tableView.mj_header endRefreshing];
                                                
                                             }];
}
- (void)sendMakeOrderButWillNotPayRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:@"other" forKey:@"from"];
    if (self.from.length) {
        [dic setObject:self.from forKey:@"from"];
    }
    [dic setObject:self.header.model.name.length?self.header.model.name:@"" forKey:@"name"];
    [dic setObject:self.header.desLable.text.length?self.header.desLable.text:@"" forKey:@"address"];
    [dic setObject:self.header.model.telephone forKey:@"telephone"];
    [dic setObject:@"wxpay" forKey:@"pay_type"];
    
    NSDictionary * shopDic = [self configOrderDic];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:shopDic options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString * finsh =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    [dic setObject:finsh forKey:@"shop"];
    
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/order/order",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"下单成功"];
                                                 [self.navigationController popViewControllerAnimated:YES];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 
                                             }];
}
@end
